<template>
  <div class="users-management" @click="closeRoleDropdown">
    <!-- 页面标题和操作栏 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div>
        <h2 class="page-title mb-1">用户管理</h2>
        <p class="text-muted mb-0">管理系统所有注册用户，支持查看、编辑、禁用等操作</p>
      </div>
      <div class="d-flex gap-2">
        <button class="btn btn-outline-secondary">
          <i class="bi bi-download me-2"></i>导出数据
        </button>
        <button class="btn btn-primary" @click="showAddUserModal">
          <i class="bi bi-plus-circle me-2"></i>添加用户
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
      <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card bg-primary text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-grow-1">
                <h4 class="card-title">{{ stats.totalUsers }}</h4>
                <p class="card-text mb-0">总用户数</p>
              </div>
              <div class="stat-icon">
                <i class="bi bi-people"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card bg-success text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-grow-1">
                <h4 class="card-title">{{ stats.activeUsers }}</h4>
                <p class="card-text mb-0">活跃用户</p>
              </div>
              <div class="stat-icon">
                <i class="bi bi-check-circle"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card bg-warning text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-grow-1">
                <h4 class="card-title">{{ stats.verifiedUsers }}</h4>
                <p class="card-text mb-0">已认证用户</p>
              </div>
              <div class="stat-icon">
                <i class="bi bi-shield-check"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card bg-info text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-grow-1">
                <h4 class="card-title">{{ stats.adminUsers }}</h4>
                <p class="card-text mb-0">管理员</p>
              </div>
              <div class="stat-icon">
                <i class="bi bi-person-gear"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="row g-3 align-items-end">
          <div class="col-md-4">
            <label class="form-label">关键词搜索</label>
            <div class="input-group">
              <span class="input-group-text">
                <i class="bi bi-search"></i>
              </span>
              <input 
                type="text" 
                class="form-control" 
                placeholder="搜索用户名、昵称、邮箱..."
                v-model="searchQuery"
                @input="handleSearch"
              >
            </div>
          </div>
          <div class="col-md-2">
            <label class="form-label">用户角色</label>
            <select class="form-select" v-model="filters.role" @change="loadUsers">
              <option value="">全部角色</option>
              <option value="user">普通用户</option>
              <option value="admin">管理员</option>
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label">认证状态</label>
            <select class="form-select" v-model="filters.isVerified" @change="loadUsers">
              <option value="">全部状态</option>
              <option value="true">已认证</option>
              <option value="false">未认证</option>
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label">账号状态</label>
            <select class="form-select" v-model="filters.status" @change="loadUsers">
              <option value="">全部状态</option>
              <option value="active">正常</option>
              <option value="disabled">禁用</option>
            </select>
          </div>
          <div class="col-md-2">
            <button class="btn btn-outline-secondary w-100" @click="resetFilters">
              <i class="bi bi-arrow-clockwise me-2"></i>重置
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">用户列表</h5>
        <div class="d-flex align-items-center gap-2">
          <span class="text-muted small">共 {{ pagination.total }} 个用户</span>
          <div class="btn-group">
            <button class="btn btn-outline-secondary btn-sm">
              <i class="bi bi-list"></i>
            </button>
            <button class="btn btn-outline-secondary btn-sm">
              <i class="bi bi-grid-3x3-gap"></i>
            </button>
          </div>
        </div>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th width="100">
                  <div class="d-flex justify-content-center align-items-center">
                    <span 
                      class="fw-bold text-primary" 
                      style="cursor: pointer; font-size: 1rem;" 
                      @click="toggleSelectAll"
                    >
                      {{ selectAll ? '取消全选' : '全选' }}
                    </span>
                  </div>
                </th>
                <th width="80">头像</th>
                <th>用户信息</th>
                <th>联系方式</th>
                <th>认证状态</th>
                <th>角色</th>
                <th>账号状态</th>
                <th>注册时间</th>
                <th width="120">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.id" :class="{ 'table-active': selectedUsers.includes(user.id) }">
                <td>
                  <div class="form-check">
                    <input 
                      type="checkbox" 
                      class="form-check-input form-check-input-lg" 
                      :value="user.id"
                      v-model="selectedUsers"
                      :id="'user-check-' + user.id"
                    >
                    <label class="form-check-label" :for="'user-check-' + user.id"></label>
                  </div>
                </td>
                <td>
                  <img 
                    :src="user.avatar" 
                    alt="头像" 
                    class="rounded-circle"
                    width="40"
                    height="40"
                    @error="handleImageError($event, user)"
                  >
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <strong class="text-primary">用户名：{{  user.username }}</strong>
                    <small class="text-muted">ID: {{ user.id }}</small>
                    <small class="text-truncate" style="max-width: 150px;" :title="user.username">
                      昵称：{{ user.nickname || '暂无简介' }}
                    </small>
                  </div>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <span class="small">
                      <i class="bi bi-envelope me-1"></i>{{ user.email }}
                    </span>
                    <span class="small" v-if="user.phone">
                      <i class="bi bi-phone me-1"></i>{{ user.phone }}
                    </span>
                    <span class="small" v-if="user.studentId">
                      <i class="bi bi-person-badge me-1"></i>{{ user.studentId }}
                    </span>
                  </div>
                </td>
                <td>
                  <span class="badge" :class="user.isVerified ? 'bg-success' : 'bg-secondary'">
                    <i class="bi me-1" :class="user.isVerified ? 'bi-check-circle' : 'bi-x-circle'"></i>
                    {{ user.isVerified ? '已认证' : '未认证' }}
                  </span>
                </td>
                <td>
                  <span class="badge" :class="user.role === 'admin' ? 'bg-danger' : 'bg-primary'">
                    <i class="bi me-1" :class="user.role === 'admin' ? 'bi-shield-check' : 'bi-person'"></i>
                    {{ user.role === 'admin' ? '管理员' : '普通用户' }}
                  </span>
                </td>
                <td>
                  <span class="badge" :class="user.status === 'active' ? 'bg-success' : 'bg-warning'">
                    <i class="bi me-1" :class="user.status === 'active' ? 'bi-check-circle' : 'bi-slash-circle'"></i>
                    {{ user.status === 'active' ? '正常' : '禁用' }}
                  </span>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <small class="text-muted">{{ formatDate(user.createdAt) }}</small>
                    <small v-if="user.lastLoginTime" class="text-info">
                      最后登录: {{ formatDate(user.lastLoginTime) }}
                    </small>
                  </div>
                </td>
                <td>
                  <div class="btn-group btn-group-sm">
                    <button 
                      class="btn btn-outline-primary"
                      @click="editUser(user)"
                      title="编辑"
                    >
                      <i class="bi bi-pencil"></i>
                    </button>
                    <button 
                      class="btn" 
                      :class="user.status === 'active' ? 'btn-outline-warning' : 'btn-outline-success'"
                      @click="toggleUserStatus(user)"
                      :title="user.status === 'active' ? '禁用用户' : '启用用户'"
                    >
                      <i class="bi" :class="user.status === 'active' ? 'bi-person-slash' : 'bi-person-check'"></i>
                    </button>
                    <button 
                      class="btn btn-outline-danger"
                      @click="deleteUser(user)"
                      title="删除"
                    >
                      <i class="bi bi-trash"></i>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 空状态 -->
        <div v-if="users.length === 0" class="text-center py-5">
          <i class="bi bi-people display-1 text-muted"></i>
          <p class="text-muted mt-3">暂无用户数据</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="card-footer d-flex justify-content-between align-items-center">
        <div class="text-muted small">
          显示第 {{ (pagination.currentPage - 1) * pagination.pageSize + 1 }} 到 
          {{ Math.min(pagination.currentPage * pagination.pageSize, pagination.total) }} 条，共 {{ pagination.total }} 条
        </div>
        <nav>
          <ul class="pagination pagination-sm mb-0">
            <li class="page-item" :class="{ disabled: pagination.currentPage === 1 }">
              <button class="page-link" @click="changePage(pagination.currentPage - 1)">
                <i class="bi bi-chevron-left"></i>
              </button>
            </li>
            <li 
              v-for="page in pagination.pages" 
              :key="page"
              class="page-item"
              :class="{ active: page === pagination.currentPage }"
            >
              <button class="page-link" @click="changePage(page)">{{ page }}</button>
            </li>
            <li class="page-item" :class="{ disabled: pagination.currentPage === pagination.totalPages }">
              <button class="page-link" @click="changePage(pagination.currentPage + 1)">
                <i class="bi bi-chevron-right"></i>
              </button>
            </li>
          </ul>
        </nav>
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div v-if="selectedUsers.length > 0" class="batch-actions fixed-bottom bg-primary text-white p-4 shadow-lg">
      <div class="container-fluid">
        <div class="row align-items-center">
          <div class="col">
            <span class="h5 mb-0 text-white">已选择 <strong>{{ selectedUsers.length }}</strong> 个用户</span>
          </div>
          <div class="col-auto">
            <div class="btn-group">
              <!-- 合并的启用/禁用按钮 -->
              <button class="btn btn-warning btn-lg me-2 text-white" @click="batchToggleUsers">
                <i class="bi bi-person-slash me-2"></i>批量切换状态
              </button>
              
              <!-- 批量修改认证状态按钮 -->
              <div class="btn-group me-2" role="group">
                <button type="button" 
                        class="btn btn-success btn-lg" 
                        @click="toggleSelectedUsersVerification">
                  <i class="bi bi-shield-check me-2"></i>批量修改认证
                </button>
              </div>
              
              <!-- 修改批量修改角色按钮 -->
              <div class="btn-group me-2" role="group">
                <button type="button" 
                        class="btn btn-info btn-lg" 
                        @click="toggleSelectedUsersRole">
                  <i class="bi bi-person-badge me-2"></i>批量修改角色
                </button>
              </div>
              
              <button class="btn btn-danger btn-lg" @click="batchDeleteUsers">
                <i class="bi bi-trash me-2"></i>批量删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加用户模态框 -->
    <div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="addUserModalLabel">添加新用户</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form>
              <div class="mb-3">
                <label for="username" class="form-label">用户名</label>
                <input type="text" class="form-control" id="username" v-model="newUser.username" required>
              </div>
              <div class="mb-3">
                <label for="nickname" class="form-label">昵称</label>
                <input type="text" class="form-control" id="nickname" v-model="newUser.nickname">
              </div>

              <div class="mb-3">
                <label for="password" class="form-label">密码</label>
                <input type="password" class="form-control" id="password" v-model="newUser.password" required>
              </div>

              
              <div class="mb-3">
                <label for="role" class="form-label">角色</label>
                <select class="form-select" id="role" v-model="newUser.role">
                  <option value="user">普通用户</option>
                  <option value="admin">管理员</option>
                </select>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="addUser">添加用户</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getUserListService, 
          batchUpdateUserStatusService, 
          batchUpdateUserRoleService,
          batchUpdateUserVerificationService,
          deleteUsersService,
          addUserService } from '@/api/user.js'

// 引入Bootstrap的Modal组件
import { Modal } from 'bootstrap'

// 添加 ElMessage 组件用于显示提示信息
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const router = useRouter()
const users = ref([])//用户列表
const selectedUsers = ref([])//批量操作的选中用户
const searchQuery = ref('')//关键字搜索
// 等待添加的用户信息
const newUser = reactive({
  username: '',
  nickname: '',
  password: '',
  role: 'user'
})

// 筛选条件
const filters = reactive({
  role: '',
  isVerified: '',
  status: ''
})

// 统计数据
const stats = reactive({
  totalUsers: 0,
  activeUsers: 0,
  verifiedUsers: 0,
  adminUsers: 0
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  totalPages: 0,
  pages: []
})

const showRoleDropdown = ref(false)

// 添加关闭下拉菜单的方法
const closeRoleDropdown = () => {
  showRoleDropdown.value = false
}

// 计算属性
const selectAll = computed({
  get: () => users.value.length > 0 && selectedUsers.value.length === users.value.length,
  set: (value) => {
    if (value) {
      selectedUsers.value = users.value.map(user => user.id)
    } else {
      selectedUsers.value = []
    }
  }
})

// 切换全选状态
const toggleSelectAll = () => {
  if (selectAll.value) {
    // 如果已经全选，则取消全选
    selectedUsers.value = []
  } else {
    // 如果没有全选，则全选所有用户
    selectedUsers.value = users.value.map(user => user.id)
  }
}

// 添加用户相关方法
const showAddUserModal = () => {
  // 重置表单
  newUser.username = ''
  newUser.nickname = ''
  newUser.email = ''
  newUser.password = ''
  newUser.phone = ''
  newUser.studentId = ''
  newUser.role = 'user'
  
  // 显示模态框
  const addUserModal = new Modal(document.getElementById('addUserModal'))
  addUserModal.show()
}

// 添加用户
const addUser = async () => {
  try {
    const response = await addUserService(newUser)
    if (response.code === 0) {
      await loadUsers()
      // 关闭模态框
      const addUserModalEl = document.getElementById('addUserModal')
      const addUserModal = Modal.getInstance(addUserModalEl) || new Modal(addUserModalEl)
      addUserModal.hide()
      ElMessage.success('用户添加成功')
    } else {
      ElMessage.error('添加用户失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('添加用户失败: ' + error.message)
  }
}

// 方法
const loadUsers = async () => {
    // 获取用户列表
  try {
    // const params = {
    //   page: pagination.currentPage,
    //   pageSize: pagination.pageSize,
    //   search: searchQuery.value,
    //   ...filters
    // }

    // 调用API获取用户数据
    const response = await getUserListService()
    if (response.code === 0) {
      // 应用所有筛选条件
      let filteredUsers = response.data
      
      // 关键字搜索
      if (searchQuery.value) {
        const keyword = searchQuery.value.toLowerCase()
        filteredUsers = filteredUsers.filter(user => 
          (user.username && user.username.toLowerCase().includes(keyword)) ||
          (user.nickname && user.nickname.toLowerCase().includes(keyword)) ||
          (user.email && user.email.toLowerCase().includes(keyword)) ||
          (user.phone && user.phone.includes(keyword))
        )
      }
      
      // 角色筛选
      if (filters.role) {
        filteredUsers = filteredUsers.filter(user => user.role === filters.role)
      }
      
      // 认证状态筛选
      if (filters.isVerified !== '') {
        // 将字符串转换为布尔值进行比较
        const isVerified = filters.isVerified === 'true'
        filteredUsers = filteredUsers.filter(user => user.isVerified === isVerified)
      }
      
      // 账号状态筛选
      if (filters.status) {
        filteredUsers = filteredUsers.filter(user => user.status === filters.status)
      }
      
      // 更新用户列表和分页信息
      users.value = filteredUsers
      pagination.total = filteredUsers.length
      pagination.totalPages = Math.ceil(pagination.total / pagination.pageSize)
      updatePaginationPages()
      updateStats()
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
  }
}

// 统计数据
const updateStats = () => {
  // 基于当前筛选后的用户列表计算统计
  stats.totalUsers = users.value.length
  stats.activeUsers = users.value.filter(user => user.status === 'active').length
  stats.verifiedUsers = users.value.filter(user => user.isVerified).length
  stats.adminUsers = users.value.filter(user => user.role === 'admin').length
}

// 分页
const updatePaginationPages = () => {
  const pages = []
  const startPage = Math.max(1, pagination.currentPage - 2)
  const endPage = Math.min(pagination.totalPages, startPage + 4)
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  pagination.pages = pages
}

// 分页
const changePage = (page) => {
  if (page >= 1 && page <= pagination.totalPages && page !== pagination.currentPage) {
    pagination.currentPage = page
    loadUsers()
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadUsers()
}

// 批量操作
const resetFilters = () => {
  searchQuery.value = ''//关键字搜索
  filters.role = ''//用户角色
  filters.isVerified = ''//认证状态
  filters.status = ''//账号状态
  pagination.currentPage = 1//重置页码
  loadUsers()//重新加载用户列表
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 用户操作
const handleImageError = (event) => {
  event.target.src = new URL('@/assets/images/头像加载失败.jpg', import.meta.url).href
}

const editUser = (user) => {
  // 跳转到用户详情页面
  router.push(`/admin/users/${user.id}`)
}

// 切换单个用户状态
const toggleUserStatus = async (user) => {
  try {
    const newStatus = user.status === 'active' ? 'banned' : 'active'
    const response = await batchUpdateUserStatusService([user.id], newStatus)
    
    if (response.code === 0) {
      user.status = newStatus
      updateStats()
      // 添加操作成功提示
      ElMessage.success(newStatus === 'active' ? '用户已启用' : '用户已禁用')
    } else {
      // 添加操作失败提示
      ElMessage.error(newStatus === 'active' ? '启用用户失败: ' + response.msg : '禁用用户失败: ' + response.msg)
    }
  } catch (error) {
    // 添加异常提示
    ElMessage.error('操作失败: ' + error.message)
  }
}

// 批量切换用户状态（启用/禁用）
const batchToggleUsers = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择用户')
    return
  }
  
  try {
    // 创建两个数组分别存储需要启用和禁用的用户ID
    const usersToEnable = []
    const usersToDisable = []
    
    // 分别收集需要启用和禁用的用户
    users.value
      .filter(user => selectedUsers.value.includes(user.id))
      .forEach(user => {
        if (user.status === 'active') {
          usersToDisable.push(user.id)
        } else {
          usersToEnable.push(user.id)
        }
      })
    
    let successCount = 0
    
    // 批量启用用户
    if (usersToEnable.length > 0) {
      const response = await batchUpdateUserStatusService(usersToEnable, 'active')
      if (response.code === 0) {
        // 更新本地用户状态
        users.value.forEach(user => {
          if (usersToEnable.includes(user.id)) {
            user.status = 'active'
          }
        })
        successCount += usersToEnable.length
      }
    }
    
    // 批量禁用用户
    if (usersToDisable.length > 0) {
      const response = await batchUpdateUserStatusService(usersToDisable, 'banned')
      if (response.code === 0) {
        // 更新本地用户状态
        users.value.forEach(user => {
          if (usersToDisable.includes(user.id)) {
            user.status = 'banned'
          }
        })
        successCount += usersToDisable.length
      }
    }
    
    selectedUsers.value = []
    updateStats()
    // 添加操作成功提示
    ElMessage.success(`成功切换 ${successCount} 个用户状态`)
  } catch (error) {
    // 添加异常提示
    ElMessage.error(`批量切换用户状态失败: ` + error.message)
  }
}

// 切换选中用户的认证状态
const toggleSelectedUsersVerification = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择用户')
    return
  }
  
  try {
    // 创建两个数组分别存储需要设为已认证和未认证的用户ID
    const usersToVerify = []
    const usersToUnverify = []
    
    // 分别收集需要设为已认证和未认证的用户
    users.value
      .filter(user => selectedUsers.value.includes(user.id))
      .forEach(user => {
        if (user.isVerified) {
          usersToUnverify.push(user.id)
        } else {
          usersToVerify.push(user.id)
        }
      })
    
    let successCount = 0
    
    // 批量设为已认证
    if (usersToVerify.length > 0) {
      const response = await batchUpdateUserVerificationService(usersToVerify, true)
      if (response.code === 0) {
        // 更新本地用户认证状态显示
        users.value.forEach(user => {
          if (usersToVerify.includes(user.id)) {
            user.isVerified = true
          }
        })
        successCount += usersToVerify.length
      }
    }
    
    // 批量设为未认证
    if (usersToUnverify.length > 0) {
      const response = await batchUpdateUserVerificationService(usersToUnverify, false)
      if (response.code === 0) {
        // 更新本地用户认证状态显示
        users.value.forEach(user => {
          if (usersToUnverify.includes(user.id)) {
            user.isVerified = false
          }
        })
        successCount += usersToUnverify.length
      }
    }
    
    selectedUsers.value = []
    updateStats()
    // 添加操作成功提示
    ElMessage.success(`成功切换 ${successCount} 个用户认证状态`)
  } catch (error) {
    // 添加异常提示
    ElMessage.error('批量更新用户认证状态失败: ' + error.message)
  }
}

// 切换选中用户的角色
const toggleSelectedUsersRole = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择用户')
    return
  }
  
  try {
    // 创建两个数组分别存储需要设为管理员和普通用户的用户ID
    const usersToAdmin = []
    const usersToUser = []
    
    // 分别收集需要设为管理员和普通用户的用户
    users.value
      .filter(user => selectedUsers.value.includes(user.id))
      .forEach(user => {
        if (user.role === 'admin') {
          usersToUser.push(user.id)
        } else {
          usersToAdmin.push(user.id)
        }
      })
      
    // 批量切换用户角色
    let successCount = 0
    
    // 批量设为管理员
    if (usersToAdmin.length > 0) {
      const response = await batchUpdateUserRoleService(usersToAdmin, 'admin')
      if (response.code === 0) {
        // 更新本地用户角色显示
        users.value.forEach(user => {
          if (usersToAdmin.includes(user.id)) {
            user.role = 'admin'
          }
        })
        successCount += usersToAdmin.length
      }
    }
    
    // 批量设为普通用户
    if (usersToUser.length > 0) {
      const response = await batchUpdateUserRoleService(usersToUser, 'user')
      if (response.code === 0) {
        // 更新本地用户角色显示
        users.value.forEach(user => {
          if (usersToUser.includes(user.id)) {
            user.role = 'user'
          }
        })
        successCount += usersToUser.length
      }
    }
    
    selectedUsers.value = []
    updateStats()
    // 添加操作成功提示
    ElMessage.success(`成功切换 ${successCount} 个用户角色`)
  } catch (error) {
    // 添加异常提示
    ElMessage.error('批量更新用户角色失败: ' + error.message)
  }
}

// 删除用户
const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.nickname || user.username}" 吗？此操作不可逆！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteUsersService([user.id])
    if (response.code === 0) {
      await loadUsers()
      ElMessage.success('用户删除成功')
      selectedUsers.value = selectedUsers.value.filter(id => id !== user.id)
    } else {
      ElMessage.error('删除用户失败: ' + response.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败: ' + error.message)
    }
  }
}
// 批量删除用户
const batchDeleteUsers = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可逆！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteUsersService(selectedUsers.value)
    if (response.code === 0) {
      await loadUsers()
      ElMessage.success(`成功删除 ${selectedUsers.value.length} 个用户`)
      selectedUsers.value = []
    } else {
      ElMessage.error('批量删除用户失败: ' + response.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除用户失败: ' + error.message)
    }
  }
}



// 生命周期
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.page-title {
  color: #2c3e50;
  font-weight: 600;
}

.stat-card {
  border: none;
  border-radius: 12px;
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 2.5rem;
  opacity: 0.8;
}

.table th {
  border-top: none;
  font-weight: 600;
  color: #6c757d;
  font-size: 0.875rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.table-hover > tbody > tr:hover > td {
  background-color: #e3f2fd !important;
}

.form-check-input-lg {
  width: 1.5em;
  height: 1.5em;
  margin-top: 0;
  border: 2px solid #0d6efd;
  transition: all 0.2s ease;
}

.form-check-input-lg:checked {
  border: 3px solid #0d6efd;
  background-color: #0d6efd;
}

.form-check {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0;
}

.form-check-label {
  cursor: pointer;
  user-select: none;
}

.table > tbody > tr {
  transition: background-color 0.2s ease;
}

.batch-actions {
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  border-top: 3px solid #0d6efd !important;
  animation: slideInUp 0.3s ease-out;
}

@keyframes slideInUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-responsive {
    font-size: 0.875rem;
  }
  
  .btn-group-sm > .btn {
    padding: 0.25rem 0.5rem;
  }
  
  .stat-card .card-title {
    font-size: 1.25rem;
  }
}
</style>